package com.itzxx.huazhun.ui.login

import android.text.TextUtils
import com.itzxx.huazhun.data.repository.HttpRequestCoroutine
import com.itzxx.huazhun.ui.MainActivity
import com.itzxx.huazhun.ui.register.RegisterActivity
import com.itzxx.huazhun.utils.UserCacheHelper
import com.itzxx.library_base_ktx.base.viewmodel.BaseViewModel
import com.itzxx.library_base_ktx.callback.databind.StringObservableField
import com.itzxx.library_base_ktx.callback.livedata.BooleanLiveData
import com.itzxx.library_base_ktx.ext.request

class LoginViewModel : BaseViewModel() {

    //机构名称
    var mechanismName = StringObservableField()

    //用户名
    var username = StringObservableField()

    //密码
    var password = StringObservableField()

    val isChecked = BooleanLiveData()

    override fun onCreateViewModel() {
        super.onCreateViewModel()
        isChecked.value = true
        UserCacheHelper.getUserInfo()?.let {
            mechanismName.set(it.tenantName)
            username.set(it.username)
        }
        UserCacheHelper.getPassword().let {
            password.set(it)
        }
    }

    fun gotoRegisterActivity() {
        baseContext.value?.let { RegisterActivity.startActivity(it) }
    }

    fun gotoOffline() {
        baseContext.value?.let {
            MainActivity.startActivity(it,true)
            finish()
        }
    }

    fun doLogin() {
        //清除已经存在问题
        //默认初始化为空
        UserCacheHelper.putToken("")
        UserCacheHelper.putTenantId("")
        if (TextUtils.isEmpty(mechanismName.get())) {
            toast("请输入机构名称")
        }else if (TextUtils.isEmpty(username.get())) {
            toast("请输入账号")
        } else if (TextUtils.isEmpty(password.get())) {
            toast("请输入密码")
        } else if (!isChecked.value) {
            toast("请阅读并勾选用户《隐私政策》")
        } else {
            loadingChange.showDialog.postValue("登录中...")
            request({
                HttpRequestCoroutine.login(
                    mechanismName.get(),
                    username.get(),
                    password.get()
                )
            }, {
                baseContext.value?.let {
                    MainActivity.startActivity(it)
                    finish()
                }
                loadingChange.dismissDialog.postValue(false)
            }, {
                toast(it.errorMsg)
                loadingChange.dismissDialog.postValue(false)
            })
        }

    }
}